package com.he.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.he.entity.LoginUser;
import com.he.entity.User;
import com.he.mapper.MenuMapper;
import com.he.mapper.RoleMapper;
import com.he.mapper.UserMapper;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Objects;

/**
 * @author He
 * @version 1.0
 * @Date 2023/9/7 13:58
 * @Desc 实现SpringSecurity提供的接口，用于查询用户信息
 */
@Service("userDetailServiceImp")
public class UserDetailServiceImpl implements UserDetailsService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private MenuMapper menuMapper;

    @Resource
    private RoleMapper roleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username);
        User user = userMapper.selectOne(queryWrapper);
        if (Objects.isNull(user)) {
            throw new RuntimeException("用户不存在");
        }
        List<String> roleList = roleMapper.selectRoleListByUserId(user.getId());
        List<String> permissionList = menuMapper.selectPermsByUserId(user.getId());
        return new LoginUser(user, permissionList, roleList);
    }
}

